package com.sws.customer.ball.impl;

import com.sws.customer.ball.WxCustomerBinder;
import com.sws.customer.domain.RyCustomer;
import com.sws.customer.mapper.RyCustomerMapper;
import com.sws.customer.service.IRyCustomerService;
import com.sws.device.domain.DevDevice;
import com.sws.device.service.IDevDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

/**
 * 微信用户与顾客记录绑定实现类
 */
@Component
public class WxCustomerBinderImpl implements WxCustomerBinder {

    private static final Logger logger = LoggerFactory.getLogger(WxCustomerBinderImpl.class);

    @Autowired
    private IRyCustomerService ryCustomerService;
    
    @Autowired
    private IDevDeviceService devDeviceService;

    @Autowired
    private RyCustomerMapper ryCustomerMapper;
    /**
     * 绑定微信用户到顾客记录
     * @param name 姓名
     * @param phone 电话号码
     * @param openid 微信openid
     * @return 处理结果
     */
    @Override
    public Map<String, Object> bindWxUserToCustomer(String name, String phone, String openid) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 构造查询条件
            RyCustomer queryCustomer = new RyCustomer();
            queryCustomer.setName(name);
            queryCustomer.setPhone(phone);

            // 查询匹配的顾客
            List<RyCustomer> customers = ryCustomerMapper.selectRyCustomerList(queryCustomer);

            if (customers == null || customers.isEmpty()) {
                // 如果找不到匹配的用户，返回错误信息
                result.put("success", false);
                result.put("msg", "未查询到指定顾客，请重新输入正确的姓名和电话号码");
            } else {
                // 找到匹配的顾客，更新openid
                RyCustomer customer = customers.get(0);

                // 检查是否已经有openid绑定
                if (customer.getOpenid() != null && !customer.getOpenid().isEmpty() &&
                        !customer.getOpenid().equals(openid)) {
                    // 已经绑定了不同的openid，提示可能是重复绑定
                    result.put("success", false);
                    result.put("msg", "该顾客已经绑定了其他微信账号，请联系管理员");
                    return result;
                }

                // 只更新OpenID和更新时间
                RyCustomer updateCustomer = new RyCustomer();
                updateCustomer.setId(customer.getId());
                updateCustomer.setOpenid(openid);
                updateCustomer.setUpdateTime(new Date());

                // 直接调用Mapper更新OpenID，避免Service层的复杂逻辑
                int rows = ryCustomerMapper.updateOpenidById(updateCustomer);

                if (rows > 0) {
                    result.put("success", true);
                    result.put("msg", "绑定成功，已关联到您的账户");
                    // 返回用户基本信息
                    Map<String, Object> userInfo = new HashMap<>();
                    userInfo.put("name", customer.getName());
                    userInfo.put("phone", customer.getPhone());
                    userInfo.put("vipLevel", customer.getVipLevel());
                    result.put("data", userInfo);

                    logger.info("顾客绑定微信成功：name={}, phone={}, openid={}", name, phone, openid);
                } else {
                    result.put("success", false);
                    result.put("msg", "绑定用户失败");
                }
            }
        } catch (Exception e) {
            logger.error("处理顾客绑定微信请求时发生错误", e);
            result.put("success", false);
            result.put("msg", "处理绑定请求时发生错误: " + e.getMessage());
        }

        return result;
    }


    
    /**
     * 验证顾客身份
     * @param openid 微信openid
     * @return 验证结果，包含顾客信息
     */
    @Override
    public Map<String, Object> verifyCustomerIdentity(String openid) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 构造查询条件
            RyCustomer queryCustomer = new RyCustomer();
            queryCustomer.setOpenid(openid);
            
            // 查询匹配的顾客
            List<RyCustomer> customers = ryCustomerService.selectRyCustomerList(queryCustomer);
            
            if (customers != null && !customers.isEmpty()) {
                RyCustomer customer = customers.get(0);
                result.put("success", true);
                result.put("customerInfo", customer);
                return result;
            }
            
            result.put("success", false);
            result.put("msg", "未找到绑定的顾客信息");
            
        } catch (Exception e) {
            logger.error("验证顾客身份失败", e);
            result.put("success", false);
            result.put("msg", "验证身份失败：" + e.getMessage());
        }
        
        return result;
    }
} 